package com.xm.servlet.reception_desk.shopping_cart;

import com.xm.entity.Commodity;
import com.xm.entity.CommodityInsurance;
import com.xm.exception.SqlErrorException;
import com.xm.service.reception_desk.*;
import com.xm.util.DiscountConverterUtil;
import lombok.SneakyThrows;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


/**
 * 购物车
 *
 * @author 康文程
 * @date 2023-12-21 下午 04:57
 */
@WebServlet("/shopping/cart")
public class ShoppingCartServlet extends HttpServlet {
    /**
     * 用户信息Service
     */
    private final AccountInformationService service = new AccountInformationService();
    /**
     * 商品Service
     */
    private final CommodityService commodityService = new CommodityService();

    /**
     * 购物车
     *
     * @param req  an {@link HttpServletRequest} object that
     *             contains the request the client has made
     *             of the servlet
     * @param resp an {@link HttpServletResponse} object that
     *             contains the response the servlet sends
     *             to the client
     */

    @SneakyThrows(Exception.class)
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        //账号Id
        Integer accountId = Integer.parseInt(req.getParameter("accountId"));
        HttpSession session = req.getSession(false);
        //令牌
        String sessionToken = (String) session.getAttribute("token");
        //是否有令牌
        if (sessionToken != null) {
            //根据账号Id查询用户Id
            Integer informationId = service.queryByAccountId(accountId);
            System.out.println(informationId);
            //判断是否登陆
            if (informationId != null) {
                logged(req,informationId,accountId);
            } else {
                //假Id
                notLogged(req);
            }
        } else {
            //没有登陆
            notLogged(req);
        }
        req.setAttribute("randomCommodities", commodityService.getRandomCommodities());
        req.getRequestDispatcher("/WEB-INF/page/reception_desk/shopping_cart.jsp").forward(req, resp);
    }

    /**
     * 没有登陆
     *
     * @param req an {@link HttpServletRequest} object that
     *            contains the request the client has made
     *            of the servlet
     **/
    public void notLogged(HttpServletRequest req) {
        //没有登陆
        req.setAttribute("shoppingCartList", new ArrayList<>());
        req.setAttribute("accountId",0);
        req.setAttribute("status", 3);
    }
    /**
     * 已登录登陆
     *
     * @param req an {@link HttpServletRequest} object that
     *            contains the request the client has made
     *            of the servlet
     **/
    public void logged(HttpServletRequest req,Integer informationId,Integer accountId) throws SqlErrorException {
        //购物车Service
        final ShoppingCartService shoppingCartService = new ShoppingCartService();
        //商品规格Service
        final CommoditySpecificationService commoditySpecificationService = new CommoditySpecificationService();
        //商品保险Service
        final CommodityInsuranceService commodityInsuranceService = new CommodityInsuranceService();
        //用户信息Service
        final AccountInformationService accountInformationService = new AccountInformationService();

        List<com.xm.entity.ShoppingCart> shoppingCartByInformationId =
                shoppingCartService.getShoppingCartByInformationId(informationId);
        //循环打印规格id
        shoppingCartByInformationId.forEach(e -> {
            String separate = ",";
            StringBuilder commodityName =
                    new StringBuilder(e.getCommodity().getCommodityName());
            //是否有多个Ids
            if (e.getSpecificationIds().contains(separate)){
                //多个id使用,分隔
                for (String specificationId : e.getSpecificationIds().split(separate)) {
                    //循环查询规格名称
                    String specificationNameById =
                            commoditySpecificationService.getSpecificationNameById(
                                    Integer.parseInt(specificationId));
                    //规格和商品名称拼接起来
                    commodityName.append("   ").append(specificationNameById);
                }
            }else{
                //如果只有一个Id则直接查询规格名称
                String specificationNameById =
                        commoditySpecificationService.getSpecificationNameById(
                                Integer.parseInt(e.getSpecificationIds()));
                //规格和商品名称拼接起来
                commodityName.append("   ").append(specificationNameById);
            }

            String notNull = "";
            //判断用户是否购买了商品保险和是否存在多个商品保险
            if (e.getInsuranceIds() != null && e.getInsuranceIds().contains(separate)){
                ArrayList<CommodityInsurance> multipleCommodityInsuranceId = new ArrayList<>();
                //查询商品保险 存在多个Id
                for (String insuranceId : e.getInsuranceIds().split(separate)) {
                    CommodityInsurance insuranceById = commodityInsuranceService.getInsuranceById(
                            Integer.parseInt(insuranceId)
                    );
                    multipleCommodityInsuranceId.add(insuranceById);
                }
                e.setCommodityInsuranceList(multipleCommodityInsuranceId);
            }else if (!notNull.equals(e.getInsuranceIds()) && e.getInsuranceIds() != null){
                //只有一个Id
                CommodityInsurance insuranceById = commodityInsuranceService.getInsuranceById(
                        Integer.parseInt(e.getInsuranceIds())
                );
                ArrayList<CommodityInsurance> singleCommodityInsuranceId = new ArrayList<>();
                singleCommodityInsuranceId.add(insuranceById);
                e.setCommodityInsuranceList(singleCommodityInsuranceId);
            }
            if (e.getInsuranceIds() != null){
                List<CommodityInsurance> insurancesByIds =
                        commodityInsuranceService.getInsurancesByIds(e.getInsuranceIds(),e.getCommodity().getCommodityId());
                e.setMerchandiseInsuranceNotAddedList(insurancesByIds);
            }

            //重新放入
            e.setCommodity(new Commodity(e.getCommodity().getCommodityId(),
                    commodityName.toString(),
                    e.getCommodity().getCommodityImages(),
                    e.getCommodity().getCommodityState(),
                    e.getCommodity().getCommodityDiscount() == 0 ? e.getCommodity().getCommodityPrice() :
                            DiscountConverterUtil.calculateDiscount(e.getCommodity().getCommodityPrice(), e.getCommodity().getCommodityDiscount()) ));
        });

        //传给前端
        req.setAttribute("informationId", informationId);
        //用户名称
        req.setAttribute("name",accountInformationService.getNameByInformationId(informationId));
        req.setAttribute("accountId",accountId);
        req.setAttribute("shoppingCartList", shoppingCartByInformationId);
        req.setAttribute("isItemsShoppingCartSelected",shoppingCartService.hasSelectedShoppingCart(informationId));

        if (shoppingCartByInformationId.size() == 0) {
            //已登录但购物车没有数据
            req.setAttribute("status", 1);
        } else {
            //已登录 购物车有数据
            req.setAttribute("status", 2);
        }
    }
}
